<template>
  <div class="pager-container" v-if="pageNumber > 1">
    <a href="#" @click="handleClick(1, $event)" :class="{ disabled: current === 1 }"
      >首页</a
    >
    <a
      href="#"
      :class="{ disabled: current === 1 }"
      @click="handleClick(current - 1)"
      >上一页</a
    >

    <a
      href="#"
      v-for="(n, i) in numbers"
      :key="n"
      :class="{
        active: n === current,
      }"
      @click="handleClick(n)"
      >{{ n }}</a
    >

    <a
      href="#"
      :class="{ disabled: current === pageNumber }"
      @click="handleClick(current + 1)"
      >下一页</a
    >
    <a
      href="#"
      :class="{ disabled: current === pageNumber }"
      @click="handleClick(pageNumber)"
      >尾页</a
    >
  </div>
</template>

<script>
export default {
  name: "Pager",
  data() {
    return {
      key: 0,
    };
  },
  props: {
    // 当前页码
    current: {
      type: Number,
      default: 1,
    },
    // 总数据量
    total: {
      type: Number,
      default: 0,
    },
    //  页容量
    limit: {
      type: Number,
      default: 10,
    },
    // 可见的页码数
    visibleNumber: {
      type: Number,
      default: 10,
    },
  },

  computed: {
    // 总页数
    pageNumber() {
      return Math.ceil(this.total / this.limit);
    },
    // 得到显示的最小数字
    visibleMin() {
      let min = this.current - Math.floor(this.visibleNumber / 2);
      if (min < 0) {
        min = 1;
      }
      return min;
    },
    // 得到显示的最大数字
    visibleMax() {
      let max = this.visibleMin + this.visibleNumber - 1;
      if (max > this.pageNumber) {
        max = this.pageNumber;
      }
      return max;
    },
    // 可见的数字集合
    numbers() {
      let nums = [];
      for (let n = this.visibleMin; n <= this.visibleMax; n++) {
        // nums.push({
        //   num:  n,
        //   id: this.key++
        // });
        nums.push(n);
      }
      return nums;
    },
  },
  methods: {
    /*
     * 在模板里面绑定事件
     *   @click="handleClick" 只有一个参数，事件对象
     *   @click="handleClick($event)" $event表示事件对象
     * */
    handleClick(newPage, event) {
      // 向父组件抛出事件
      if (newPage < 1) {
        newPage = 1;
      }
      if (newPage > this.pageNumber) {
        newPage = this.pageNumber;
      }
      if (newPage === this.current) {
        return;
      }
      // 向父组件抛出事件
      this.$emit("pageChange", newPage);
    },
  },
};
</script>

<style lang="less" scoped>
@import "~@/styles/var";

.pager-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;

  a {
    color: @primary;
    margin: 0 6px;

    &.disabled {
      color: @lightWords;
      cursor: not-allowed;
    }

    &.active {
      color: @words;
      cursor: text;
      font-weight: bold;
    }
  }
}
</style>